from solvers.solverbase import SolverBase
from solvers.tg.tgbase import TGBase
from dolfin import *

class LaxWendroff2(SolverBase,TGBase):
    'Lax-Wendroff Taylor-Galerkin as a two stage method.'
    def __init__(self,p=1,type=0,bcStrong=0):
        SolverBase.__init__(self,p)
        TGBase.__init__(self,type,bcStrong)

    def solve(self,problem):
        mesh = problem.domain

        V = FunctionSpace(mesh,'CG',1)
        VV = VectorFunctionSpace(mesh,'CG',1)

        phi_ = interpolate(problem.phi_,V)
        phi = TrialFunction(V)
        varphi = TestFunction(V)

        t = problem.t           
        dt = Constant(SolverBase._get_time_step(self,problem,VV,t))
        T = problem.T

        self.update(problem,phi_,t,float(dt),0)  # store the solution at time 0
        
        v = SolverBase._get_velocity(self,problem,VV,t) # velocity field
        (ib,ib_value,bParts) = problem.get_inflowBCS()  # ib_value has bc conditions on the inflow part
        g = Function(V)                                 # inflow bcs for the weak form
        n = FacetNormal(mesh)
        phi_1 = Function(V)                             # solution of stage 1
        
        a = phi*varphi*dx         # common lhs for both stages
        bcStrong = self.bcStrong != 0                   # enforcing boundary condition strongly on the inflow
        if self.type == 0:
            '''weakly enforced bcs on inflow'''
            l1 = phi_*varphi*dx \
                -0.5*dt*(inner(v,nabla_grad(phi_))*varphi*dx + 0.5*(abs(inner(v,n))-inner(v,n))*(phi_-g)*varphi*ds)
            l2 = phi_*varphi*dx \
                -dt*(inner(v,nabla_grad(phi_1))*varphi*dx + 0.5*(abs(inner(v,n))-inner(v,n))*(phi_1-g)*varphi*ds)

        elif self.type == 1:
            '''bcs strongly'''
            l1 = phi_*varphi*dx \
                -0.5*dt*inner(v,nabla_grad(phi_))*varphi*dx
            l2 = phi_*varphi*dx \
                -dt*inner(v,nabla_grad(phi_1))*varphi*dx

        A = assemble(a)     
        phi = Function(V)
   
        t = 0
        count = 0

        while t <= T:
            t += float(dt)
            count += 1
            g.vector()[:] = interpolate(ib_value(t),V).vector().array() # update inflow values
            
            L1 = assemble(l1) 
            
            if bcStrong:
                ibc = DirichletBC(V,ib_value(t),ib)  # apply the inflow boundary conditions 
                ibc.apply(A,L1)         
            
            solve(A,phi.vector(),L1)
            phi_1.assign(phi)


            L2 = assemble(l2)
            
            if bcStrong:
                ibc = DirichletBC(V,ib_value(t),ib)  # apply the inflow boundary conditions 
                ibc.apply(A,L2)         
 
            solve(A,phi.vector(),L2)
            phi_.assign(phi)
            
            self.update(problem,phi_,t,float(dt),count)

        problem.save_data(self.saveDir,str(self.CFL))

